const Router = require('@koa/router');
const { TravelModel } = require("../database/index");
const { Sequelize, Op, where } = require("sequelize");
const router = new Router(); 

//添加景点
router.post('/addTravel',async(ctx,next)=>{
    const { name,desc,category,content } = ctx.request.body;
    console.log("测试", name,desc,category,content);

    const logo = ctx.files[0].filename;//获取上传的文件名
    const result = await TravelModel.create({
        name,desc,category,content,logo
    });
    console.log(result.toJSON());
    if (result) {
        ctx.body = {
            code: 200,
            msg: "添加成功",
        };
    } else {
        ctx.body = {
            code: 500,
            msg: "添加失败",
        };
    }
})

// 查询景点
router.get('/getAllTravelByPage', async (ctx, next) => {
    const { category, name, currentPage, pageSize } = ctx.query;
    const condition1 = name ? { name: { [Op.like]: `%${name}%` } } : null;
    const condition2 = category ? { category: { [Op.eq]: category } } : null;

    const { count, rows } = await TravelModel.findAndCountAll({
        where: Object.assign({}, condition1, condition2),
        offset: (currentPage - 1) * pageSize,
        limit: parseInt(pageSize)
    },)
    ctx.body = {
        code: 200,
        msg: "获取数据成功!!!",
        data: {
            rows: rows,
            count: count
        }
    };
});

// 删除景点
router.post('/handleDelete', async (ctx, next) => {
    const { travelId } = ctx.request.body;
    try {
        const result = await TravelModel.destroy({
            where: {
                travelId: travelId
            }
        });
        if (result) {
            ctx.body = {
                code: 200,
                msg: "删除成功"
            };
        } else {
            ctx.body = {
                code: 201,
                msg: "删除失败"
            };
        }
    } catch (error) {
        ctx.body = {
            code: 500,
            msg: "删除失败"
        };
    }
});

// 修改景点
router.post("/updateTravel", async (ctx, next) => {
    const { travelId,name,desc,category,content } = ctx.request.body;
    console.log("测试", travelId,name,desc,category,content);
    const logo = ctx.files[0].filename;//获取上传的文件名
  
    try {
        const result = await TravelModel.update(
            { name,desc,category,content,logo },
            { where: { travelId: travelId } }
        );
        console.log(result);
        if (result) {
            ctx.body = {
                code: 200,
                msg: "更新成功",
            };
        } else {
            ctx.body = {
                code: 500,
                msg: "更新失败",
            };
        }
  
    } catch (error) {
        console.log(error);
        ctx.body = {
            code: 501,
            msg: "更新失败",
        };
    }
  });
  
module.exports = router